package sevelet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {
    UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");
        switch (method){
            case "checkUsername":
                checkUsername(request,response);
                break;
            case "registerUser":
                registerUser(request,response);
                break;
        }
    }
    private void checkUsername(HttpServletRequest request, HttpServletResponse
            response) throws IOException {
        String username = request.getParameter("username");
        boolean b =userService.checkUsercame(username);
//使用Map存放给前端的结果
        Map<String, String> resultMap = new HashMap<>();
        if(b){
            resultMap.put("result","USERNAME_EXIST");
            String r= JSON.toJSONString(resultMap);
        }else{
            resultMap.put("result","USERNAME_CAN_USE");
            String r= JSON.toJSONString(resultMap);
        }
//将结果转换为json，便于前端处理
        response.setContentType("application/json");
        PrintWriter out=response.getWriter();
        out.print(JSONObject.toJSONString(resultMap));
    }
    private void registerUser(HttpServletRequest request, HttpServletResponse
            response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        boolean b = userService.add(username, password);
//使用Map存放给前端的结果
        Map<String, String> resultMap = new HashMap<String, String>();
        if(b){
            resultMap.put("result","REGISTER_SUCCESS");
        }else{
            resultMap.put("result","REGISTER_FAIL");
        }
//将结果转换为json，便于前端处理
        response.setContentType("application/json");
        PrintWriter out=response.getWriter();
        out.print(JSONObject.toJSONString(resultMap));
    }



            @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);

    }
}
